package cn.herlioner.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;


import cn.herlioner.dao.StudentDAO;
import cn.herlioner.pojo.TSObject;
import cn.herlioner.pojo.Student;

public class StudentDAOImpl implements StudentDAO{

	@Override
	public void add(Student s) {
		SessionFactory sf = new Configuration().configure()
				.buildSessionFactory();
		Session se = sf.openSession();
		se.beginTransaction();
		
		se.save(s);
		
		se.getTransaction().commit();
		se.close();
		sf.close();
		
	}

	@Test
	public Student get(Long long1) {
		Student result = null;
		Configuration configuration = new Configuration();
		configuration.configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
        result = (Student) session.get(Student.class, long1);
        session.close();
        sessionFactory.close();
        return result;
	}

	@Override
	public void delete(Long stunum) {
		SessionFactory sf = new Configuration().configure()
                .buildSessionFactory();
        Session s = sf.openSession();
        s.beginTransaction();
 
        Student st = (Student) s.get(Student.class, stunum);
 
        s.delete(st);
 
        s.getTransaction().commit();
        s.close();
        sf.close();
		
	}

	@Override
	public void update(Student s) {
		 SessionFactory sf = new Configuration().configure()
	                .buildSessionFactory();
	        Session se = sf.openSession();
	        se.beginTransaction();
	 
	        se.update(s);
	 
	        se.getTransaction().commit();
	        se.close();
	        sf.close();
		
	}
	@Override
	public List<Student> list() {
		List<Student> result = new ArrayList<Student>();
		 
        SessionFactory sf = new Configuration().configure()
                .buildSessionFactory();
        Session s = sf.openSession();
 
        Query q = s.createQuery("from Student s");
 
        result = q.list();
 
        s.close();
        sf.close();
        return result;
	}



	@SuppressWarnings("unchecked")
	@Override
	public List<Student> list(List<Student> students) {
		List<Student> result = new ArrayList<Student>();
		 
        SessionFactory sf = new Configuration().configure()
                .buildSessionFactory();
        Session s = sf.openSession();
 
        Query q = s.createQuery("from Student s");
        if(students == null){
        	result = q.list();
        }else{
        	result = students;
        	result = q.list();
        }
        s.close();
        sf.close();
        return result;
	}

	}
